#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from odoorpc.error import RPCError

from utility.api_security import APISecurity
from authlib.jose import jwt
from datetime import datetime, timedelta
import time
from utility.error_code import error_code
import odoorpc
from settings import ODOO_HOST, ODOO_PORT, ODOO_DB, SECRET_KEY
import logging

_logger = logging.getLogger(__name__)


class WebLoginAPI(Resource):
    """
    验证用户名和密码，并返回登录态token
    :request: get
    :param login: 用户名
    :param password: 密码
    :returns: json string
    """

    _transient_max_hours = 7 * 24  # token失效时间

    def post(self):
        try:
            odoo = odoorpc.ODOO(ODOO_HOST, port=ODOO_PORT)
            odoo.login(ODOO_DB, request.json['login'], request.json['password'])
            user = odoo.env.user

            # 生成token aud：接收人 uid：接收人id exp：过期时间戳
            header = {'typ': 'JWT', 'alg': 'HS256'}  # 签名算法
            exp_date = datetime.now() + timedelta(seconds=self._transient_max_hours * 3600)
            struct_time = exp_date.timetuple()  # struct_time类型
            exp = int(time.mktime(struct_time))
            payload = {'aud': user.id, 'login': request.json['login'], 'pwd': request.json['password'], 'exp': exp}
            token = jwt.encode(header=header, payload=payload, key=SECRET_KEY)  # byte类型

            return jsonify({'code': 0, 'msg': 'success', 'data': {'token': token.decode()}})
        except RPCError as e:
            if (e.info['data']['name'] == 'odoo.exceptions.AccessDenied'):
                return jsonify({
                    'code': 1,
                    'msg': '用户名或密码错误，请重试'
                })
        except AttributeError as e:
            _logger.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            _logger.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})
        finally:
            odoo.logout()


class WebCheckTokenAPI(Resource):
    """
    根据token校验登录态，用于APP端登录校验
    :request: get
    :param token: Token
    :returns: json string
    """

    def get(self):
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})

            return jsonify({'code': 0, 'msg': 'success', 'data': {'user_id': payload['aud']}})
        except AttributeError as e:
            _logger.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            _logger.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})
